﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Exusiai.Editor.Models;
using Avalonia.Exusiai.Editor.ViewModels;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using Avalonia.ReactiveUI;
using ReactiveUI;

namespace Avalonia.Exusiai.Editor.Views;

public partial class ProjectFileView : ReactiveUserControl<ProjectFileViewModel>
{
    public ProjectFileView()
    {
        InitializeComponent();
        DataContext=new ProjectFileViewModel();
        this.WhenActivated(d =>
        {
            d(ViewModel.SelectFolderInteraction.RegisterHandler(InteractionHandler));
        });
    }


    private async Task InteractionHandler(InteractionContext<string?, string[]?> context)
    {
        // Get our parent top level control in order to get the needed service (in our sample the storage provider. Can also be the clipboard etc.)
        var topLevel = TopLevel.GetTopLevel(this);

        var storageFolders = await topLevel!.StorageProvider
            .OpenFolderPickerAsync(
                new FolderPickerOpenOptions
                {
                    AllowMultiple = false,
                    Title = context.Input
                });

        context.SetOutput(storageFolders?.Select(x => x.Path.AbsolutePath).ToArray());
    }

    private void InputElement_OnPointerPressed(object? sender, PointerPressedEventArgs e)
    {
        if(e.ClickCount==2)
        {
            Console.Out.WriteLine("sender = {0}", sender);
        }
    }

    private void FileListBox_OnDoubleTapped(object? sender, TappedEventArgs e)
    {
        var listBox = sender as ListBox;
        var selectedItem = listBox?.SelectedItem as FileListViewModel;
        var selectedNode = selectedItem?.Node;
        ViewModel.OpenSelectedFolderCommand.Execute(selectedNode);
    }

    private void Grid_OnTapped(object? sender, TappedEventArgs e)
    {
        var node = sender as Grid;
        var selectedNode = node?.DataContext as Node;
        ViewModel.OpenSelectedFolderCommand.Execute(selectedNode);
    }
}